package com.espirit.eap.sa;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.googlecode.cswish.annotation.ParamScope;
import com.googlecode.cswish.annotation.ScopeValue;
import com.googlecode.cswish.model.PageInfo;
import com.googlecode.cswish.model.ParameterMap;
import com.googlecode.cswish.model.Reference;
import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.spring.GenericService;
import com.googlecode.cswish.struts.spring.ObjectFactory;

@Service
public class TemplateService {
	
	@Resource
	private PrivilegeService privilegeService;
	
	@Resource
	private GenericService genericService;
	
	@Resource
	private ObjectFactory objectFactory;
	
	public PageInfo search(ParameterMap model, int start, int limit, String sort, String dir,
			boolean newSearch, Reference<QLInfo> qlInfoRef) {
		model.setParameter("class", "2");
		PageInfo pageInfo = genericService.search(model, start, limit, sort, dir, newSearch, qlInfoRef);
		return pageInfo;
	}
	
	public void _add(Template model,
			@ParamScope(scopeKey="'Privilege.applySelectedPrivileges'", visible=false, scope=ScopeValue.SESSION)
				Reference<UserTemplate> selectedPrivileges) {
		selectedPrivileges.set(null);
//		Website website = objectFactory.getBean(UserService.class, false).getCurrentWebsite();
//		model.setDefaultWebsite(website);
	}
	
	public Object _update(Template model, 
			@ParamScope(scopeKey="'Privilege.applySelectedPrivileges'", visible=false, scope=ScopeValue.SESSION)
				Reference<UserTemplate> selectedPrivileges) {
		selectedPrivileges.set(null);
		
		Template template = genericService.view(model);
//		if (model.getDefaultWebsite() == null) {
//			Website website = objectFactory.getBean(UserService.class, false).getCurrentWebsite();
//			model.setDefaultWebsite(website);
//		}
		return template;
	}
	
	@Transactional
	public void add(Template model, List<String> privileges,
			@ParamScope(scopeKey="'Privilege.applySelectedPrivileges'", visible=false, scope=ScopeValue.SESSION)
			Reference<UserTemplate> selectedPrivileges) {
		update(model, privileges, selectedPrivileges);
	}
	
	@Transactional
	public void update(Template model, List<String> privileges,
			@ParamScope(scopeKey="'Privilege.applySelectedPrivileges'", visible=false, scope=ScopeValue.SESSION)
			Reference<UserTemplate> selectedPrivileges) {
		UserTemplate userTemplate = selectedPrivileges.get();
		if (userTemplate != null) {
			selectedPrivileges.set(null);
			userTemplate.setId(model.getId());
			// use the template as the draft version
			UserTemplate dbTemplate = genericService.merge(userTemplate);
			model.setId(dbTemplate.getId());
		}
		
		// apply the user modification to the template
		privilegeService.update(model, privileges);
	}
}
